//
//  SocketManager.m
//  GCDSocketServer
//
//  Created by chenf on 2022/5/22.
//

#import "SocketManager.h"
#import "GCDAsyncSocket.h"

@interface SocketManager()

@property(nonatomic,strong)NSMutableArray *clientSocketes;
@property(nonatomic,strong)NSMutableDictionary *registerClientSocketes;
@end

@implementation SocketManager

+ (SocketManager *)sharedSocketManager{
    static SocketManager *socket = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        socket = [[SocketManager alloc] init];
    });
    return socket;
}
-(id)init{
    self =[super init];
    if(self){
        self.clientSocketes = [NSMutableArray arrayWithCapacity:0];
        self.registerClientSocketes = [NSMutableDictionary dictionary];
    }
    return self;;
}
-(NSArray *)currentExistSocketes{
    return  [NSArray arrayWithArray:self.clientSocketes];
}
-(NSDictionary *)currentExistRegisterSocketes{
    return  [NSDictionary dictionaryWithDictionary:self.registerClientSocketes];
}
//注册用户
-(void)addClicent:(GCDAsyncSocket * __nonnull)socket userId:(NSString * __nonnull)userId{
    if(userId!=nil&&userId.length>0 && socket!=nil){
        self.registerClientSocketes[userId] = socket;
    }
}
#pragma  mark
-(void)addClicent:(GCDAsyncSocket *)socket{
    //有可能存在，过期
    if(socket!=nil){
        [self.clientSocketes addObject:socket];
        NSLog(@"添加Socket链接:%@",socket);
    }
}
-(void)removeClicent:(GCDAsyncSocket *)socket key:(NSString* __nullable)key{
    if(socket.isConnected){
        [socket disconnect];
    }
    if(socket!=nil&&self.clientSocketes.count>0&&[self.clientSocketes containsObject:socket]){
        [self.clientSocketes removeObject:socket];
        NSLog(@"移除Socket链接By Object:%@",socket);
    }
    if(key&&key.length>1){
        [self.registerClientSocketes removeObjectForKey:key];
        NSLog(@"移除Socket链接 By Key :%@",key);
    }
}
-(void)clearAll{
    if(self.clientSocketes.count>0){
        @autoreleasepool {
            //主动断开客户端链接
            for(GCDAsyncSocket *clientSocket  in self.clientSocketes){
                if(clientSocket.isConnected){
                    [clientSocket disconnect];
                }else{
                    NSLog(@"[%@] 链接已经断开",clientSocket);
                }
            }
            [self.clientSocketes removeAllObjects];
            [self.registerClientSocketes removeAllObjects];
        }
    }
}
@end
